package com.nokia.pc3.core.dac;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

import com.nokia.pc3.core.format.input.RpmDatum;
import com.nokia.pc3.core.xform.TransformFactory;
import com.nokia.pc3.core.xform.XformLabelOut;
import com.nokia.pc3.core.xform.Xformation;

/**
 * Nokia transformer memory map object used by transformers and writer.
 * 
 * @author jcroke
 * 
 */
public class NokiaUmem {

	private final Map<String, Object> uMem;
	private final Map<String, Object> oMem;
	private final Stack<RpmDatum> rpmStk = new Stack<RpmDatum>();

	public NokiaUmem() {
		uMem = new HashMap<String, Object>();
		oMem = new HashMap<String, Object>();
	}

	public final Object get(String key) {
		return (uMem.get(key));
	}

	public final void put(String key, Object value) {
		uMem.put(key, value);
	}

	public void setLabelOutput(Xformation xfm) {
		if (null != xfm) {
			ArrayList<XformLabelOut> xfol = xfm.getXformOutList();
			Collections.sort(xfol);
			for (XformLabelOut xfo : xfol) {
				oMem.put(xfo.getLabelOut(), uMem.get(xfo.getLabelIn()));
			}
		} else {
			oMem.put(TransformFactory.DEFAULT_NOP_OUTPUT,
					uMem.get(TransformFactory.DEFAULT_NOP_INPUT));
		}
	}

	/**
	 * Replace contents of internal map with output map. Clears output map.
	 */
	public void swap() {
		Set<String> omemK = oMem.keySet();
		// Do not perform the swap if the oMem is empty.
		if (!omemK.isEmpty()) {
			uMem.clear();
			for (String k : omemK) {
				uMem.put(k, oMem.get(k));
			}
			oMem.clear();
		}
	}
	
	public Stack<RpmDatum> getRpmStk() {
		return rpmStk;
	}

	public Map<String, Object> getOutput() {
		swap();
		return uMem;
	}
}
